package com.jxl.springboot.game.utils;

import com.jxl.springboot.game.web.constant.Constant;
import org.apache.logging.log4j.util.Strings;
import org.springframework.util.StringUtils;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Cookie 设置工具类
 * @author 江雪林
 * @create 2021-04-23
 */
public class CookieUtils {
    public static final String PATH = "/";
    public static final Integer SENDS = 60;
    /**
     * 添加 Cookie
     * @param resp
     * @param name
     * @param value
     * @param expire 有效时间 s
     */
    public static void addCookie(HttpServletResponse resp,String name,String value,Integer expire){
        if(Strings.isBlank(name) || Strings.isBlank(value) || resp==null){
            return;
        }
        Cookie ucookie = new Cookie(name, value);
        ucookie.setPath(Constant.PATH);
        ucookie.setHttpOnly(true);
        if(expire==null){
            ucookie.setMaxAge(SENDS);
        }else if(expire == -1){
            ucookie.setMaxAge(-1);
        }else if (expire>-1){
            ucookie.setMaxAge(expire);
        }
        resp.addCookie(ucookie);
    }

    /**
     * 使 Cookie 过期
     * @param resp
     * @param name
     */
    public static void expireCookie(HttpServletResponse resp, HttpServletRequest req, String name){
        if(Strings.isBlank(name) || resp == null|| resp == null){
            return;
        }
        Cookie[] cookies = req.getCookies();
        if (cookies!=null){
            for(Cookie cookie:cookies){
                if(cookie.getName().equals(name)){
                    cookie.setMaxAge(0);
                    cookie.setValue("");
                    cookie.setPath(PATH);
                    resp.addCookie(cookie);
                    return;
                }
            }
        }
    }

    /**
     * 获取 Cookie 的值
     * @param req
     * @param name
     * @return
     */
    public static String getCookieValueByName(HttpServletRequest req,String name){
        if(Strings.isBlank(name) || req==null){
            return null;
        }
        Cookie[] cookies = req.getCookies();
        if (cookies!=null){
            for(Cookie cookie:cookies){
                if (cookie.getName().equals(name)){
                    return cookie.getValue();
                }
            }
        }
        return null;
    }
}
